package com.atguigu.crowd.handle;

import com.atguigu.crowd.api.MySQLReomteService;
import com.atguigu.crowd.config.OSSProperties;
import com.atguigu.crowd.constant.CrowdConstan;
import com.atguigu.crowd.entity.vo.*;
import com.atguigu.crowd.util.CrowdUtil;
import com.atguigu.crowd.util.ResultEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigurationPackage;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zzqstart
 * @Description
 * @date 2022-09-20 14:38
 */
@Controller
public class ProjectConsumerHandler {

    @Autowired
    private OSSProperties ossProperties;

    @Autowired
    private MySQLReomteService mySQLReomteService;

    @RequestMapping("/get/project/detail/{projectId}")
    public String getProjectDetail(@PathVariable("projectId") Integer projectId, Model model) {
        ResultEntity<DetailProjectVO> resultEntity = mySQLReomteService.getDetailProjectVORemote(projectId);
        if (ResultEntity.SUCCESS.equals(resultEntity.getResult())) {
            DetailProjectVO detailProjectVO = resultEntity.getData();
            model.addAttribute("detailProjectVO", detailProjectVO);
        }
        return "project-show-detail";
    }

    @RequestMapping("/create/confirm")
    public String saveConfirm(
            MemberConfirmInfoVO memberConfirmInfoVO,
            HttpSession session,
            Model model
    ) {
        if (memberConfirmInfoVO == null) {
            return "project-confirm";
        }
        // 获取ProjectVO对象
        ProjectVO projectVO = (ProjectVO) session.getAttribute(CrowdConstan.ATTR_NAME_TEMPLE_PROJECT);
        if (projectVO == null) {
            throw new RuntimeException(CrowdConstan.MESSAGE_TEMPLE_PROJECT_MISSING);
        }
        projectVO.setMemberConfirmInfoVO(memberConfirmInfoVO);

        // 获取当前用户信息
        MemberLoginVo memberLoginVO = (MemberLoginVo) session.getAttribute(CrowdConstan.ATTR_NAME_LOGIN_MEMBER);
        Integer memberId = memberLoginVO.getId();
        // 调用远程方法保存到数据库
        ResultEntity<String> resultEntity = mySQLReomteService.saveProjectVORemote(projectVO, memberId);
        if (ResultEntity.FALIED.equals(resultEntity.getResult())) {
            model.addAttribute(CrowdConstan.ATTR_NAME_MESSAGE, resultEntity.getMessage());
            return "project-confirm";
        }
        // 7.将临时的 ProjectVO 对象从 Session 域移除
        session.removeAttribute(CrowdConstan.ATTR_NAME_TEMPLE_PROJECT);
        // 8.如果远程保存成功则跳转到最终完成页面
        return "redirect:http://localhost/project/create/success";
    }

    @ResponseBody
    @RequestMapping("/create/save/return.json")
    public ResultEntity<String> saveReturn(
            ReturnVO returnVO,
            HttpSession session
    ) {
        try {
            // 取出之前的projectVO
            ProjectVO projectVO = (ProjectVO) session.getAttribute(CrowdConstan.ATTR_NAME_TEMPLE_PROJECT);
            // 判断projectVO是否为空
            if (projectVO == null) {
                return ResultEntity.failed(CrowdConstan.MESSAGE_TEMPLE_PROJECT_MISSING);
            }
            // 获取projectVO里面的returnVOList
            List<ReturnVO> returnVOList = projectVO.getReturnVOList();
            // returnVOList之前是否有数据
            if (returnVOList == null || returnVOList.size() == 0) {
                returnVOList = new ArrayList<>();
                projectVO.setReturnVOList(returnVOList);
            }
            // 将数据添加到returnVOList
            returnVOList.add(returnVO);
            // 将returnVOList装回projectVO
            projectVO.setReturnVOList(returnVOList);
            // 保存在session中
            session.setAttribute(CrowdConstan.ATTR_NAME_TEMPLE_PROJECT, projectVO);
            return ResultEntity.successWithoutData();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failed(e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping("/create/upload/return/picture")
    public ResultEntity<String> uploadReturnPicture(
            @RequestParam("returnPicture") MultipartFile returnPicture
    ) throws IOException {
        // 判断上传文件是否为空
        if (returnPicture.isEmpty()) {
            return ResultEntity.failed(CrowdConstan.MESSAGE_RETURNPICTURE_EMPTY);
        }
        // 上传文件
        ResultEntity<String> returnPicResultEntity = CrowdUtil.uploadFileToOss(
                ossProperties.getEndPoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret(),
                returnPicture.getInputStream(),
                ossProperties.getBucketName(),
                ossProperties.getBucketDomain(),
                returnPicture.getOriginalFilename()
        );
        if (ResultEntity.FALIED.equals(returnPicResultEntity.getResult())) {
            return ResultEntity.failed(CrowdConstan.MESSAGE_RETURN_PIC_UPLOAD_FAILED);
        }
        // 返回上传结果
        return returnPicResultEntity;
    }

    @RequestMapping("/create/project/information")
    public String saveProjectBasicInfo(
            // 接收除了上传图片之外的其他普通数据
            ProjectVO projectVO,
            // 接收上传的头图
            MultipartFile headerPicture,
            // 接收上传的详情图片
            List<MultipartFile> detailPictureList,
            // 用来将收集了一部分数据的 ProjectVO 对象存入 Session 域
            HttpSession session,
            // 用来在当前操作失败后返回上一个表单页面时携带提示消息
            Model model
    ) throws IOException {
        // 一、完成头图上传
        // 1.获取当前 headerPicture 对象是否为空
        boolean headerPictureEmpty = headerPicture.isEmpty();
        if (headerPictureEmpty) {
            // 2.如果没有上传头图则返回到表单页面并显示错误消息
            model.addAttribute(CrowdConstan.ATTR_NAME_MESSAGE, CrowdConstan.MESSAGE_HEADER_PIC_EMPTY);
            return "project-launch";
        }
        // 3.如果用户确实上传了有内容的文件，则执行上传
        ResultEntity<String> OSSResultEntity = CrowdUtil.uploadFileToOss(
                ossProperties.getEndPoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret(),
                headerPicture.getInputStream(),
                ossProperties.getBucketName(),
                ossProperties.getBucketDomain(),
                headerPicture.getOriginalFilename()
        );
        // 4.判断头图是否上传成功
        if (ResultEntity.FALIED.equals(OSSResultEntity.getResult())) {
            model.addAttribute(CrowdConstan.ATTR_NAME_MESSAGE, CrowdConstan.MESSAGE_HEADER_PIC_UPLOAD_FAILED);
            return "project-launch";
        }
        // 5.上传成功则将图片路径加入到ProjectVO
        String headerPicturePath = OSSResultEntity.getData();
        projectVO.setHeaderPicturePath(headerPicturePath);

        // 二、上传详情图片
        // 1.创建一个用来存放详情图片路径的集合
        List<String> detailPicturePath = new ArrayList<>();
        // 2.判断详细图片集合是否为空
        if (detailPictureList == null || detailPictureList.size() == 0) {
            model.addAttribute(CrowdConstan.ATTR_NAME_MESSAGE, CrowdConstan.MESSAGE_DETAIL_PIC_UPLOAD_FAILED);
            return "project-launch";
        }
        // 3.遍历详细图片
        for (MultipartFile detailPicture : detailPictureList) {
            // 判断是否为空，空则跳过此次循环
            if (detailPicture.isEmpty()) {
                continue;
            }
            // 不为空则上传
            ResultEntity<String> detailResultEntity = CrowdUtil.uploadFileToOss(ossProperties.getEndPoint(),
                    ossProperties.getAccessKeyId(),
                    ossProperties.getAccessKeySecret(),
                    detailPicture.getInputStream(),
                    ossProperties.getBucketName(),
                    ossProperties.getBucketDomain(),
                    detailPicture.getOriginalFilename()
            );
            if (ResultEntity.FALIED.equals(detailResultEntity.getResult())) {
                model.addAttribute(CrowdConstan.ATTR_NAME_MESSAGE, CrowdConstan.MESSAGE_DETAIL_PIC_UPLOAD_FAILED);
                return "project-launch";
            }
            String detailPictureFileName = detailResultEntity.getData();
            detailPicturePath.add(detailPictureFileName);
        }
        // 将上传成功的路径存入projectVo
        projectVO.setDetailPicturePathList(detailPicturePath);
        // 三、后续操作
        // 通过session存入redis，实现session共享
        session.setAttribute(CrowdConstan.ATTR_NAME_TEMPLE_PROJECT, projectVO);
        // 2.以完整的访问路径前往下一个收集回报信息的页面
        return "redirect:http://localhost/project/return/info/page";
    }
}
